package com.jiutong.meipenggang.utils;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

import com.jiutong.meipenggang.base.BaseActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作用:
 * Created by 78 on 2017/8/23.
 */

public class SmsObserver extends ContentObserver {

    private Handler mHandler;
    private Context mContext;

    public SmsObserver(Context context, Handler handler){
        super(handler);
        this.mContext = context;
        this.mHandler = handler;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
//        if(uri.toString().equals("content://sms/raw")){
//            return;
//        }

        String code = "";
        Uri uriInbox = Uri.parse("content://sms/inbox");
        Cursor cursor = mContext.getContentResolver().query(uriInbox,null,null,null,"date desc");
        if(cursor!=null){
            if(cursor.moveToNext()){
                String address = cursor.getString(cursor.getColumnIndex("address"));
                String body = cursor.getString(cursor.getColumnIndex("body"));
                Log.d("address",address);
                Log.d("body",body);
                Pattern pattern = Pattern.compile("(\\d{6})");
                Matcher matcher = pattern.matcher(body);
                if(matcher.find()){
                    code = matcher.group(0);
                    Log.d("code",code);
                    mHandler.obtainMessage(BaseActivity.MSG_CODE,code).sendToTarget();
                }
            }
            cursor.close();
        }
    }
}
